package com.xp.flower.qsd.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.xp.flower.api.IWeiXinTokenService;
import com.xp.flower.common.dto.WeiXinTokenDTO;
import com.xp.flower.qsd.utils.HttpUtils;
import com.xp.flower.qsd.utils.weixin.WeiXinGlobalConstants;

@Component
public class WeChatTask {
    
    @Autowired
    private IWeiXinTokenService weiXinTokenService;
    
    private static final Logger logger = LoggerFactory.getLogger(WeChatTask.class);
    
    @Scheduled(cron="0 0 0/2 * * ?")   //每2个小时秒执行一次  
//    @Scheduled(cron="0 0/1 * * * ?")   //每分钟执行一次
    public void getAccessToken() {
        try {
            logger.info("WeChatTack run getAccessToken start " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            Map<String, String> params = new HashMap<String, String>();
            params.put("grant_type", WeiXinGlobalConstants.getProperties("grant_type"));
            params.put("appid", WeiXinGlobalConstants.getProperties("appid"));
            params.put("secret", WeiXinGlobalConstants.getProperties("secret"));
            String jstoken = HttpUtils.sendGet(WeiXinGlobalConstants.getProperties("tokenUrl"), params);
            String access_token = JSON.parseObject(jstoken).getString("access_token");
            WeiXinGlobalConstants.getProperties().put("access_token", access_token);
            
            WeiXinTokenDTO weiXinTokenDTO = new WeiXinTokenDTO();
            weiXinTokenDTO.setCreatetime(System.currentTimeMillis());
            weiXinTokenDTO.setAccessToken("7BZcxDViRV_gQTO0Xv4uHIKM-Na4QTSJH4oio7wxDC1N6VC7PWwRS56Y6MGbw42lUt_U60quNrBV2rKUrDSmgBTVtQFoM-6s_aWxlDtmtmJizKyziTNpZrtyQKzyQSZUDKJdAAATAZ");
            weiXinTokenService.insertWeiXinToken(weiXinTokenDTO);
            
            logger.info("WeChatTack run getAccessToken success access_token : " + access_token);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("WeChatTack run getAccessToken error" + e.getMessage());
        }
    }
    
    
}
